#!/bin/bash
set -e

CWD=$(pwd -P)
cleanup()
{
    EXIT=$?
    set +e
    echo Stopping rancher server
    kill $PID
    wait $PID
    echo Cleanup DIND
    TESTS="$CWD/$(dirname $0)/../tests"
    for dindYML in $(find $TESTS -iname 'dind-*.yml'); do
        rke remove --dind --force --config $dindYML
        rm -f $dindYML
    done
    if [ $EXIT -ne 0 ]; then
        echo '***RANCHER LOGS***'
        cat $CWD/rancherlogs.txt
        echo '***END RANCHER LOGS***'
    fi
    return $EXIT
}

#[ "${ARCH}" == "amd64" ] && RACE=-race
go test -cover -tags=test .././...

if [ ${ARCH} == arm64 ]; then
    export ETCD_UNSUPPORTED_ARCH=arm64
fi

echo Starting rancher server
$(dirname $0)/run &> $CWD/rancherlogs.txt &
PID=$!
trap cleanup exit

while ! curl -sf http://localhost:8080/ping; do
    sleep 2
done

echo Running tests

cd $(dirname $0)/../tests/integration
tox -- -m "not nonparallel" -n $(nproc)
tox -- -m nonparallel
